<?php

namespace app\admin\controller\account;

use app\common\controller\Backend;
use http\Exception;
use think\Db;

/**
 * 账户转账记录
 *
 * @icon fa fa-circle-o
 */
class Record extends Backend
{

    /**
     * Record模型对象
     * @var \app\admin\model\account\Record
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\account\Record;
        $this->view->assign("oarTypeList", $this->model->getOarTypeList());
        $this->view->assign("oarAccountTypeList", $this->model->getOarAccountTypeList());
        $this->view->assign("oarStatusList", $this->model->getOarStatusList());
        $this->view->assign("StatusList", $this->model->getStatusList());
    }

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->where(['oar_es_id'=>$this->auth->es_id,'oar_is_deleted'=>0])
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }




    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function orderaccountrecord(){
        if (false === $this->request->isPost()) {
            $id = $this->request->param('id');
            $order_model = new  \app\admin\model\select\Order();
            $row    = $order_model->find($id);
            $this->view->assign('row',$row);
            $this->view->assign('id',$id);
            return $this->view->fetch();
        }
        $this->saveRecord();

    }



    public function saveRecord(){
        $params = $this->request->post('row/a');
        $id = $params['id']??0;
        $out_account_title  = $params['oar_out_account_title']??'';
        $in_account_title   = $params['oar_in_account_title']??'';
        $account_money      = $params['oar_money']??0;
        $account_note       = $params['oar_note']??'';
        $account_type       = $params['account_type']??0;
        if(!$account_money){
            $this->error(__('请输入金额'));
        }

        $status = $params['status']??0; //1.转入 2.转出
        $type   = $params['type']??0; //1.出入库转账


        Db::startTrans();
        try {
            //出入库转账需要判断订单金额
            if($type == 1){

                $insert = [
                    'oar_es_id'        => $this->auth->es_id,
                    'oar_order_id'     => $id,
                    'oar_money'        => $account_money,
                    'oar_note'         => $account_note,
                    'oar_status'       => $status,
                    'oar_type'         => $type,
                    'oar_create_time'  => time(),
                    'oar_account_type'  => $account_type,
                    'oar_out_account_title'  => $out_account_title,
                    'oar_in_account_title'  => $in_account_title,
                ];
            }

            $ret = $this->model->save($insert);

            //处理订单是否已清账
            $this->model->saveOrderSettled($id);
            Db::commit();
            $this->success();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error('记录失败');
        }
    }



    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
                $this->model->saveOrderSettled($item['oar_order_id']);
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }

}
